package mapEditor.common
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import helper.LoaderHelper;
	import helper.URLLoaderHelper;
	
	import mapEditor.events.MapEditorEvent;

	public class MapAssetManager extends EventDispatcher
	{
		private var _loader:LoaderHelper;
		private var _urlLoader:URLLoaderHelper;
		private var _path:String;
		private var _xmlConfig:XML;
		
		
		public function MapAssetManager()
		{
		}
		
		/**
		 * 注册地图资源类
		 */		
		public function register(path:String=null):void
		{
			if(path) loadConfig(path);
		}
		
		/**
		 * 载入地图资源 
		 * @param path 地图资源配置文件路径
		 * 
		 */		
		public function loadConfig(path:String):void
		{
			_path=path;
			_urlLoader=new URLLoaderHelper(_path, 0, onConfigCallBack);
			_urlLoader.loadSync();
		}
		
		private function onConfigCallBack(data:*):void
		{
			_xmlConfig=new XML(data);
			if(!_xmlConfig) return;
			
			_loader=new LoaderHelper(_xmlConfig.@path, 0, onLoadAssetCallBack, _xmlConfig);
			var loaderContext:LoaderContext=new LoaderContext();
//			loaderContext.allowLoadBytesCodeExecution=true;
			loaderContext.applicationDomain=ApplicationDomain.currentDomain;
			_loader.loadSync(loaderContext);
		}
		
		private function onLoadAssetCallBack(data:*):void
		{
			dispatchEvent(new MapEditorEvent(MapEditorEvent.MAP_ASSET_LOAD_COMPLETE, data.data));
		}
		
		public static function getAssetByType(link:String):*
		{
			if(ApplicationDomain.currentDomain.hasDefinition(link))
			{
				var classAsset:Class=ApplicationDomain.currentDomain.getDefinition(link) as Class;
				if(!classAsset) return null;
				return new classAsset();
			}
			else
			{
				return null;
			}
		}
		
		public function dispose():void
		{
			_xmlConfig=null;
			if(_loader)
			{
				if(_loader.parent) _loader.parent.removeChild(_loader);
				_loader.dispose();
			}
			_loader=null;
			
			if(_urlLoader) _urlLoader.dispose();
			_urlLoader=null;
		}

		public function get path():String
		{
			return _path;
		}

		public function set path(value:String):void
		{
			_path = value;
		}

	}
}